import {ChangeDetectorRef, Component, OnInit, TemplateRef} from '@angular/core';
import {NzNotificationService} from 'ng-zorro-antd/notification';
import {TauriEventService} from "./tauri-event.service";

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    notifyMsg = "请先按输入框的提示操作";
    inputValue = "";
    scanFilePath = "扫描中";
    list: string[] = [];
    loading: boolean = false;
    scanFileNum = 0;
    scanFileComplete = false;
    scanSecond = "";
    scanFileResult: ScanFileResult[] = [];
    fileModel: FileModel[] = [];
    startTime: Date = new Date();

    constructor(private notification: NzNotificationService,
                private tauriEventService: TauriEventService,
                private changeDetectorRef: ChangeDetectorRef) {

    }


    ngOnInit(): void {
        this.tauriEventService.listen('file-item').subscribe(e => {
            this.fileItemEventHandler(e);
        });
        this.tauriEventService.listen('file_list_result').subscribe(e => {
            this.fileListResultEventHandler(e);
        });
    }

    onStart(template: TemplateRef<{}>): void {
        this.scanFileComplete = false;
        if (this.loading) {
            this.notifyMsg = `正在停止任务`;
            this.stopTask();
            this.notification.template(template);
            return;
        }
        if (this.list.length == 0) {
            this.notification.template(template);
            return;
        }

        if (this.list.length > 0) {
            this.notifyMsg = `开始扫描，目录个数为： ${this.list.length}`;
        }
        this.notification.template(template);
        this.startTime = new Date();
        this.scanFileNum = 0;
        this.tauriEventService.sendCommand('file_list', {dir: this.list[0]})
            .subscribe(
                {
                    next: res => {
                        console.log("file_list2 -> ", res);
                    },
                    error: err => {
                        console.log("file_list2Err", err);
                    }
                }
            )
        this.loading = true;
    }

    sortByFileSize(list: ScanFileResult[]) {
        return list.sort((a, b) => {
            return b.files[0].size - a.files[0].size;
        });
    }


    public stopTask() {
        console.log("stopTask");
        this.tauriEventService.sendCommand('stop', {dir: this.list[0]})
            .subscribe(
                {
                    next: res => {
                        console.log("onStopResp", res);
                    },
                    error: err => {
                        console.log(" stopErr", err);
                    },
                    complete: () => {
                        this.loading = false;
                    }
                }
            )
    }

    onKeypress(e: any) {
        if (e.key === 'Enter' && this.inputValue) {
            console.log("onkeypress", e);
            console.log("inputValue:", this.inputValue);
            let newList = this.list;
            newList.push(this.inputValue);
            this.list = newList;
            this.inputValue = "";
        }
    }

    delDir(item: string) {
        this.list = this.list.filter(i => i != item);
    }

    private fileItemEventHandler(event: any) {
        console.log("fileItemEventHandler: ", event.payload);
        this.scanFilePath = event.payload.path;
        this.scanFileNum += 1;
        // this.notifyView();
    }

    private fileListResultEventHandler(event: any) {
        console.log("fileListResultEventHandler : ", event.payload);
        let endTime = new Date();
        let t = endTime.getTime() - this.startTime.getTime();
        this.scanSecond = this.formatSeconds(t / 1000);
        this.loading = false;
        this.scanFileComplete = true;
        let list = event.payload as ScanFileResult[];
        this.scanFileResult = this.sortByFileSize(list);
        this.fileModel = this.scanFileResult.map(i => {
            let first = i.files[0];
            return {
                md5: i.md5,
                name: first.file_name,
                num: i.files.length,
                size: first.size,
                sizeStr: this.formatFileSize(first.size),
                path: i.files.map(f => f.file_path),
            };
        });
        console.log("fileListResultSortSuccess");
        // this.notifyView();
    }

    private notifyView() {
        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();
    }

    /**
     * 将秒数换成时分秒格式
     */
    formatSeconds(secondTime: number) {
        let minuteTime = 0;// 分
        let hourTime = 0;// 小时
        if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = parseInt(String(secondTime / 60));
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = parseInt(String(secondTime % 60));
            //如果分钟大于60，将分钟转换成小时
            if (minuteTime > 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseInt(String(minuteTime / 60));
                //获取小时后取佘的分，获取分钟除以60取佘的分
                minuteTime = parseInt(String(minuteTime % 60));
            }
        }
        let result = "" + parseInt(String(secondTime)) + " 秒";

        if (minuteTime > 0) {
            result = "" + parseInt(String(minuteTime)) + " 分" + result;
        }
        if (hourTime > 0) {
            result = "" + parseInt(String(hourTime)) + " 小时" + result;
        }
        return result;
    }

    formatFileSize(fileSize: number) {
        if (fileSize < 1024) {
            return fileSize + ' B';
        } else if (fileSize < (1024 * 1024)) {
            return (fileSize / 1024).toFixed(2) + ' KB';
        } else if (fileSize < (1024 * 1024 * 1024)) {
            return (fileSize / (1024 * 1024)).toFixed(2) + ' MB';
        } else {
            return (fileSize / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
        }
    }


}

export interface ScanFile {
    file_name: string,
    size: number,
    file_path: string,
    extension: string,
}

export interface ScanFileResult {
    md5: string,
    files: ScanFile[]
}

export interface FileModel {
    md5: string;
    name: string;
    num: number;
    size: number;
    sizeStr: string;
    path: string[];
}


